<!-- AssignmentTeacher.vue -->
<template>
  <div class="assignment-container">
    <el-card class="assignment-card">
      <template #header>
        <div class="card-header">
          <h3>作业管理</h3>

        </div>
      </template>

      <!-- 作业列表 -->
      <el-table
        :data="assignments"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        border
        stripe>
        <el-table-column prop="title" label="作业标题" min-width="200">
          <template #default="{ row }">
            <div class="assignment-title">
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="due_date" label="截止日期" width="180">
          <template #default="{ row }">
            <div class="due-date">
              <i class="el-icon-time"></i>
              {{ formatDate(row.due_date) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="满分" width="100">
          <template #default="{ row }">
            <el-tag type="success">{{ row.score }}分</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submission_stats" label="提交情况" width="150">
          <template #default="{ row }">
            <div class="submission-stats">
              <el-progress
                :percentage="getSubmissionPercentage(row.submission_stats)"
                :format="(percentage) => `${row.submission_stats.submitted}/${row.submission_stats.total}`"
                :status="getProgressStatus(row.submission_stats)">
              </el-progress>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button
                type="primary"
                size="small"
                @click="openPendingAssignmentsDialog(row.id)">
                批改作业
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="viewAssignmentDetail(row.id)">
                查看详情
              </el-button>
              <el-dropdown>
                <el-button size="small">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="openEditDialog(row)">
                      <i class="el-icon-edit"></i> 编辑
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click="confirmDeleteAssignment(row.id)"
                      class="delete-option">
                      <i class="el-icon-delete"></i> 删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="openCreateDialog" class="create-btn" >
           创建新作业
          </el-button>
    </el-card>

    <!-- 作业提交列表弹窗 -->
    <AssignmentSubmissionDialog
      v-model:visible="submissionListDialogVisible"
      :submissions="sortedSubmissionList"
      @close="submissionListDialogVisible = false"
      @grade="openGradeSubmissionDialog"
    />
    <!-- 批改作业弹窗 -->
    <AssignmentGradingDialog
  v-model:visible="gradingDialogVisible"
  :assignment-id="currentAssignmentId"
  @graded="handleGraded"
/>
    <!-- 作业详情弹窗 -->
    <AssignmentDetailDialog
      v-model:visible="detailDialogVisible"
      :assignment="assignmentDetail"
      @close="handleClose1"
    />
    <!-- 作业表单弹窗 -->
    <AssignmentFormDialog
  v-model:visible="assignmentDialogVisible"
  :form="assignmentForm"
  :is-edit="isEdit"
  :file-list="fileList"
  :submission-stats="currentAssignmentStats"
  @submit="submitAssignment"
  @update:file-list="updateFileList"
  @remove-attachment="handleRemoveAttachment"
/>

    <!-- 删除确认弹窗 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
      center>
      <div class="delete-confirmation">
        <i class="el-icon-warning"></i>
        <p>确定要删除这个作业吗？此操作无法撤销。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
           <el-button type="danger" @click="deleteAssignment">确定删除</el-button>
          <el-button @click="deleteDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import AssignmentSubmissionDialog from '@/components/assignment/AssignmentSubmissionDialog.vue'
import AssignmentDetailDialog from '@/components/assignment/AssignmentDetailDialog.vue'
import AssignmentFormDialog from '@/components/assignment/AssignmentFormDialog.vue'
import AssignmentGradingDialog from "@/components/assignment/AssignmentGradingDialog.vue";

// 定义 props
const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  }
})

// 状态管理
const peerReviewDialogVisible = ref(false)
const currentSubmissionId = ref(null)
const assignments = ref([])
const currentAssignmentId = ref(null)
const assignmentDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const submissionListDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const gradingDialogVisible = ref(false)
const isEdit = ref(false)
const fileList = ref([])
const assignmentDetail = ref(null)
const sortedSubmissionList = ref([])
let assignmentToDelete = null
const existingAttachments = ref([])
const currentAssignmentStats = ref({
  total: 0,
  submitted: 0
})

const assignmentForm = reactive({
  id: null,
  title: '',
  description: '',
  due_date: '',
  score: 100,
  is_peer_review_enabled: false,
  peer_review_count: 2,
  peer_review_due_date: '' // 新增字段
})

// 获取作业列表
const fetchAssignments = async () => {
  try {
    const response = await axios.get(`/backend/api/assignment/course/${props.courseId}/list/`, {
      withCredentials: true
    })
    assignments.value = response.data
  } catch (error) {
    console.error('获取作业列表失败:', error)
    ElMessage.error('获取作业列表失败，请稍后重试')
  }
}

const getSubmissionPercentage = (stats) => {
  if (!stats || !stats.total) return 0
  return Math.round((stats.submitted / stats.total) * 100)
}
//打开互评记录
const openPeerReviewDialog = (assignmentId) => {
  currentSubmissionId.value = assignmentId
  peerReviewDialogVisible.value = true
}
const getProgressStatus = (stats) => {
  if (!stats || !stats.total) return ''
  const percentage = (stats.submitted / stats.total) * 100
  if (percentage === 100) return 'success'
  if (percentage >= 80) return ''
  if (percentage >= 50) return ''
  return 'warning'
}

// 提交作业表单
const submitAssignment = async () => {
  try {
    const url = isEdit.value
      ? `/backend/api/assignment/${assignmentForm.id}/update/`
      : '/backend/api/assignment/create/'

    const requestData = {
      course: props.courseId,
      title: assignmentForm.title,
      description: assignmentForm.description,
      due_date: new Date(assignmentForm.due_date).toISOString(),
      score: assignmentForm.score,
      is_peer_review_enabled: assignmentForm.is_peer_review_enabled
    }

    if (assignmentForm.is_peer_review_enabled === true) {
      requestData.peer_review_count = assignmentForm.peer_review_count
      requestData.peer_review_due_date = new Date(assignmentForm.peer_review_due_date).toISOString()
    }

    const response = await axios({
      method: isEdit.value ? 'patch' : 'post',
      url: url,
      data: requestData,
      headers: { 'Content-Type': 'application/json' },
      withCredentials: true
    })

    if (response.status === 200 || response.status === 201) {
      // 如果有新的附件要上传
      if (fileList.value.length > 0) {
        try {
          await uploadAttachments(isEdit.value ? assignmentForm.id : response.data.id)
        } catch (error) {
          ElMessage.warning('作业创建成功，但附件上传失败，请稍后在编辑中重试')
          assignmentDialogVisible.value = false
          await fetchAssignments()
          return
        }
      }

      ElMessage.success(`${isEdit.value ? '作业更新' : '作业创建'}成功`)
      assignmentDialogVisible.value = false
      await fetchAssignments()
    }
  } catch (error) {
    console.error(`${isEdit.value ? '更新作业' : '创建作业'}失败:`, error)
    ElMessage.error(`${isEdit.value ? '更新作业' : '创建作业'}失败，请稍后重试`)
  }
}

// 处理附件上传
const uploadAttachments = async (assignmentId) => {
  if (!fileList.value.length) return

  const formData = new FormData()
  fileList.value.forEach(file => {
    formData.append('files', file.raw)
  })

  try {
    const response = await axios.post(
      `/backend/api/assignment/${assignmentId}/attachments/upload/`,
      formData,
      {
        headers: { 'Content-Type': 'multipart/form-data' },
        withCredentials: true
      }
    )
    return response.data
  } catch (error) {
    console.error('上传附件失败:', error)
    throw new Error('上传附件失败')
  }
}
// 处理删除现有附件
const handleRemoveAttachment = async (attachmentId) => {
  try {
    await axios.delete(`/backend/api/assignment/attachment/${attachmentId}/delete/`, {
      withCredentials: true
    })
    existingAttachments.value = existingAttachments.value.filter(
      attachment => attachment.id !== attachmentId
    )
    ElMessage.success('附件删除成功')
  } catch (error) {
    console.error('删除附件失败:', error)
    ElMessage.error('删除附件失败，请稍后重试')
  }
}
// 删除作业
const deleteAssignment = async () => {
  try {
    const response = await axios.delete(`/backend/api/assignment/${assignmentToDelete}/delete/`, {
      withCredentials: true
    })
    if (response.status === 200) {
      ElMessage.success('作业删除成功')
      deleteDialogVisible.value = false
      await fetchAssignments()
    }
  } catch (error) {
    console.error('删除作业失败:', error)
    ElMessage.error('删除作业失败，请稍后重试')
  }
}

// 获取作业详情
const fetchAssignmentDetail = async (assignmentId) => {
  try {
    const response = await axios.get(`/backend/api/assignment/${assignmentId}/detail/`, {
      withCredentials: true
    })
    assignmentDetail.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取作业详情失败:', error)
    ElMessage.error('获取作业详情失败，请稍后重试')
  }
}

// 打开待批改作业列表
const openPendingAssignmentsDialog = async (assignmentId) => {
  currentAssignmentId.value = assignmentId
  gradingDialogVisible.value = true
}

// 工具方法
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// UI 操作方法
const openCreateDialog = () => {
  isEdit.value = false
  // 重置统计信息
  currentAssignmentStats.value = { total: 0, submitted: 0 }

  Object.assign(assignmentForm, {
    title: '',
    description: '',
    due_date: '',
    score: 100,
    is_peer_review_enabled: false,
     peer_review_count: null
  })
  fileList.value = []
  assignmentDialogVisible.value = true
}

const openEditDialog = (assignment) => {
  isEdit.value = true
  currentAssignmentStats.value = assignment.submission_stats || { total: 0, submitted: 0 }
  Object.assign(assignmentForm, {
    id: assignment.id,
    title: assignment.title,
    description: assignment.description,
    due_date: assignment.due_date,
    score: assignment.score,
    // 保持原有的互评状态
    is_peer_review_enabled: Boolean(assignment.is_peer_review_enabled),
    peer_review_count: assignment.peer_review_count || null
  })
  fileList.value = []
  assignmentDialogVisible.value = true
}

const viewAssignmentDetail = (id) => {
  fetchAssignmentDetail(id)
}

const confirmDeleteAssignment = (id) => {
  assignmentToDelete = id
  deleteDialogVisible.value = true
}

const handleClose1 = () => {
  detailDialogVisible.value = false
}

const updateFileList = (newFileList) => {
  fileList.value = newFileList
}

// 生命周期钩子
onMounted(() => {
  if (props.courseId) {
    fetchAssignments()
  }
})
</script>


<style scoped>
.assignment-container {
  padding: 20px;
}

.assignment-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  flex-shrink: 0;
}

.create-btn {
  flex-shrink: 0; /* 防止按钮被压缩 */
  white-space: nowrap; /* 防止按钮文字换行 */
}

.assignment-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-tag {
  margin-left: 8px;
}

.due-date {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
  align-items: center;
}

.delete-option {
  color: #f56c6c;
}

.delete-confirmation {
  text-align: center;
  padding: 20px 0;
}

.delete-confirmation i {
  font-size: 24px;
  color: #f56c6c;
  margin-bottom: 10px;
}

.delete-confirmation p {
  margin: 0;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 20px;
}
</style>